package com.zyht.website.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.wx.core.vo.SysMenuSet;
import com.wx.entity.SysMenu;
import com.wx.entity.SysWxuser;
import com.wx.model.dictionary.Constant;
import com.wx.service.SysWxuserService;
import com.wx.util.JsonResult;
import com.wx.util.JsonUtil;
import com.zyht.common.AbsManageBaseController;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;
import com.zyht.website.entity.SysUser;
import com.zyht.website.service.SysUserService;
import com.zyht.website.shiro.PermissionUtils;
import com.zyht.website.shiro.UsernamePasswordToken;
import com.zyht.wechat.framework.constant.ConfigConstants;
import com.zyht.wechat.framework.env.WechatEnv;

@Controller
@RequestMapping("/admin")
public class LoginController extends AbsManageBaseController {

	private Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private SysUserService sysUserService;
	@Resource
	private SysWxuserService sysWxuserService;

	@RequestMapping(method = RequestMethod.GET,value="/login")
	public String loadHomePage(HttpServletRequest request,Model m){

		HttpSession session = request.getSession();
		Object sessionUser = session.getAttribute(sessionUserKey);
		if(null != sessionUser){
			return "redirect:/admin/index";
		}
		return "/admin/login/index";
	}

	@RequestMapping(value = "/login/anon/valid",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	public @ResponseBody String validLogin(HttpServletRequest request,HttpServletResponse response,
		@RequestParam(value = "username",required = true) final String username,@RequestParam(value = "password",required = true) final String password,
		@RequestParam(value = "verifycode",required = true) final String verifycode){

		HttpSession session = request.getSession();
		String json = "";
		String useUniversalCode = PropertiesUtils.getConfig(ConfigConstants.USE_UNIVERSAL_CODE);
		if(null == useUniversalCode || !"1".equals(useUniversalCode)){
			if(StringUtils.isEmpty(verifycode)){
				json = JsonUtil.Object2Json(JsonResult.messageJson(false,"非法的验证码"));
				return json;
			} else{
				Object sessionCode = session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
				if(null == sessionCode){
					json = JsonUtil.Object2Json(JsonResult.messageJson(false,"非法的验证码"));
					return json;
				} else if(!sessionCode.toString().equalsIgnoreCase(verifycode)){
					json = JsonUtil.Object2Json(JsonResult.messageJson(false,"验证码错误"));
					return json;
				}
				session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
			}
		}

		// 获取ip地址
		String remortIP = getIp(request);
		Subject subject = SecurityUtils.getSubject();
		if(subject.isAuthenticated()){
			return messageJson(true,"已登录");
		}
		UsernamePasswordToken token = new UsernamePasswordToken(username,password.toCharArray(),false,remortIP,"",false);
		try{
			subject.login(token);
			
			SysUser user = PermissionUtils.getUser();
			session.setAttribute(this.sessionUserKey, user);

			if(WechatEnv.isWechatConfigOk()){
				SysWxuser wxuser = WechatEnv.wxuser;
				session.setAttribute(sessionWxUserKey,wxuser);
			}
			
			List<SysMenu> menuList = PermissionUtils.getMenuList();
			List<SysMenu> menuListnew = new ArrayList<SysMenu>(menuList);
			for(Iterator<SysMenu> iterator = menuListnew.iterator();iterator.hasNext();){
				SysMenu sysMenu = iterator.next();
				if(sysMenu.getMenuShow() != null && sysMenu.getMenuShow().equals("0")){
					iterator.remove();
				}
			}

			SysMenuSet ps = new SysMenuSet(menuListnew);
			ps.toSet();
			session.setAttribute(Constant.AUTH_PURVIEW, ps);
			return messageJson(true,"登录成功");
		} catch (UnknownAccountException e){
			return messageJson(false,"用户名/密码错误");
		} catch (IncorrectCredentialsException e){
			return messageJson(false,"用户名/密码错误");
		} catch (Exception e){
			logger.error("用户:[" + username + "]" + e.getMessage());
			e.printStackTrace();
			return messageJson(false,"登录失败");
		}
	}

	@RequestMapping("/logout")
	public String logout(HttpServletRequest request,HttpSession session,Model model){

		session.removeAttribute(this.sessionUserKey);
		session.removeAttribute(this.sessionWxUserKey);
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		model.addAttribute("msg","退出成功");
		model.addAttribute("redirect","admin/login/index");
		return "message";
	}

	private String messageJson(Boolean bool,String msg){

		return JsonUtil.Object2Json(JsonResult.messageJson(bool,msg));
	}
}
